const koa = require('koa')
const views = require('koa-views')
const { resolve } = require('path')
const { connect, initSchema, initAdmin } = require('./database/init')

const R = require('ramda')
const MIDDLEWARES = ['router']

const useMiddlewares = async (app) => {
  await new Promise ((res, rej) => {
    const { addBodyParser, addLogger, addSession }  = require('./middlewares/general')
    addBodyParser(app)
    addLogger(app)
    addSession(app)
    app.use(async (ctx, next) => {

      // 设置多个跨域
      if (ctx.headers.origin === 'http://movie-web.fanchao.site' || ctx.headers.origin === 'http://video.fanchao.site') {
        ctx.set('Access-Control-Allow-Origin', ctx.headers.origin);
      }
      //ctx.set('Access-Control-Allow-Origin', ctx.headers.origin); // 设置全部跨域，注意不能写 * （因为有sessionid随请求携带，需要凭证，所以要写具体的ip,不能写*）
      //ctx.set('Access-Control-Allow-Origin', 'http://movie-web.fanchao.site');
      ctx.set('Access-Control-Allow-Credentials', true);
      ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
      ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
      await next();
    });
    res()
  })

  await new Promise ((res, rej) => {
    const { router }  = require('./middlewares/router')
    router(app)
    res()
  })
  await new Promise ((res, rej) => {
    const { func }  = require('./middlewares/parcel')
    func(app)
    res()
  })
}

;(async () => {
  await connect()

  await initSchema()

  await initAdmin()
  
  // require('./tasks/movie') // 最新电影数据
  // require('./crawler/video') // then 通过doubanId 查video
  // require('./tasks/trailer') // X
  // require('./tasks/api') // then 爬取更详细的内容（summary，movieTypes，year等）
  // require('./tasks/qiniu') // then 上传视频资源到图床

  const app = new koa()
  await useMiddlewares(app)
  // app.use(views(resolve(__dirname, './views'), {
  //   extension: 'pug'
  // }))

  // app.use(async (ctx) => {
  //   await ctx.render('index', {
  //     you: 'koa',
  //     me: 'fanchao'
  //   })
  // })

  app.listen(4455, () => {
    console.log('server run on port 4455')
  })
})()
